using Infrastructure;
using Microsoft.EntityFrameworkCore;
using MediatR;
using System.Reflection;
using NLog;
using NLog.Web;
using RabbitTraceability.Api.Filters;
using Infrastructure.Redis;
using Infrastructure.AliyunOSS;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.OpenApi.Models;
using RabbitTraceability.Api;

// 初始化NLog
var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug("初始化应用程序");

try
{
    var builder = WebApplication.CreateBuilder(args);

    // 配置NLog
    builder.Logging.ClearProviders();
    builder.Host.UseNLog();

    // 添加全局过滤器（包括异常处理和日志记录）
    builder.Services.AddGlobalFilters();

    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    //中文注释
    builder.Services.AddSwaggerGen(o =>
    {
        var file = Path.Combine(AppContext.BaseDirectory + "RabbitTraceability.Api.xml");
        o.IncludeXmlComments(file, true);
        // 显示 授权信息
        o.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme()
        {
            Description = "添加JWT授权Token：Bearer Token值",
            Name = "Authorization",
            In = Microsoft.OpenApi.Models.ParameterLocation.Header,
            Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
            BearerFormat = "JWT",
            Scheme = "Bearer"
        });
        o.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[]
            {

            }
        }
    });
    });

    // 注册HttpContext访问器，用于获取当前用户信息
    builder.Services.AddHttpContextAccessor();

    // 注册内存缓存服务
    builder.Services.AddMemoryCache();

    // 注册Redis服务
    builder.Services.AddRedisService(builder.Configuration);
    
    // 注册阿里云OSS服务
    builder.Services.AddAliyunOSSService(builder.Configuration);

    // 注册审计相关服务

    builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();
    builder.Services.AddScoped<AuditableEntitySaveChangesInterceptor>();

    //配置数据库
    builder.Services.AddDbContext<DataDbContext>(x =>
    {
        x.UseSqlServer(builder.Configuration.GetConnectionString("Conn"));
    });

    // 注册MediatR
    builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

    // 注册仓储
    builder.Services.AddScoped(typeof(IRepository<>), typeof(BaseRepository<>));

    // 注册命令处理器
    builder.Services.AddScoped<RabbitTraceability.Api.Applications.CommandHandler.QueryImageInfoCommandHandler>();
    builder.Services.AddScoped<RabbitTraceability.Api.Applications.CommandHandler.SaveBreedingInfoCommandHandler>();
    builder.Services.AddScoped<RabbitTraceability.Api.Applications.CommandHandler.QueryBreedingInfoCommandHandler>();

    // 添加跨域配置
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy", policy =>
        {
            policy.AllowAnyOrigin()
                  .AllowAnyHeader()
                  .AllowAnyMethod();
        });
    });
    builder.Services.AddAutoMapper(typeof(MapperProFile));
    // 添加JWT认证
    builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    // 使用跨域中间件
    app.UseCors("CorsPolicy");

    // 启用静态文件服务，用于访问wwwroot目录下的文件
    app.UseStaticFiles();

    // 添加认证中间件
    app.UseAuthentication();
    app.UseAuthorization();

    app.MapControllers();

    app.Run();
}
catch (Exception ex)
{
    // 记录启动过程中的异常
    logger.Error(ex, "程序启动过程中发生异常");
    throw;
}
finally
{
    // 确保在应用程序退出时正确关闭NLog
    NLog.LogManager.Shutdown();
}
